/**
 *	m.transit.js
 *	@author liuz
 *	2013.10.24
 */
(function () {
	// 添加tipsDiv元素
	var tips = $('<div id="tipsDiv">正在定位，<span class="hi">3秒</span>后将自动跳转...</div>');
	$(document.body).append(tips);

	var _rootDomainNoProtocol = 'm.58.com',
		cityName = '';	// 默认指定空值

	var getPosByIP = function () {
		var url = 'http://' + _rootDomainNoProtocol + '/ipservice/?callback=?';
		$.getJSON(url, function (data) {
			console.log('IP定位成功：' + data.listname);
			cityName = data.listname;
			if (!cityName || cityName === '-1') {
				cityName = 'bj';
			}
			$('#category a').each(function () {
				var $this = $(this);
				var href = $this.attr('href2') || '';
				$this.attr('href', href.replace('?', cityName));
			});
		});
	};
	getPosByIP();

	var getPosByGPS = function (lon, lat) {
		var url = 'http://' + _rootDomainNoProtocol + '/location/?l=' + lat + '&d=' + lon + '&callback=?';
		$.getJSON(url, function (data) {
			cityName = data.listname;
		});
	};

	var getGPS = function (callback) {
		var result = false;
		if (navigator.geolocation) {
			navigator.geolocation.getCurrentPosition(
				function (pos) {
					var lon = pos.coords.longitude,
						lat = pos.coords.latitude;
					console.log('GPS定位成功：(' + lon + ', ' + lat + ')');
					getPosByGPS(lon, lat);
				},
				function (err) {
					console.log('GPS定位失败。');
					if (!cityName) {
						getPosByIP();
					}
				}
			);
		} else {
			console.log('not support geolocation');
			if (!cityName) {
				getPosByIP();
			}
			if (typeof callback === 'function') {
				callback(result);
			}
		}
	};

	window.jump = function () {
		var href = window.location.href;
		if (href.match(/com\/(?:w\/)([a-z]*)(\/?|\.\w*)/)) {
			if (!cityName || cityName === '-1') {
				cityName = 'bj';
			}
			var cateName = RegExp.$1;
			var daleiye = '|job|jianzhi|house|sale|car|pets|piaowu|shenghuo|jiaoyou|lvyouxiuxian|hunjiehunqing|zhuangxiujc|qichefw|yiliaobaojian|canyin|xiuxianyl|liren|shangwu|zhaoshang|';
			var ext = '';
			if (daleiye.indexOf('|' + cateName + '|') >= 0) {
				ext = '.shtml';
			}
			var url = 'http://' + _rootDomainNoProtocol + '/' + cityName + '/' + cateName + ext;
			url = url.replace('/w/', '/');
			console.log('jumping to ' + url);
			window.location.href = url;
		}
	};

	getGPS();
	setTimeout(jump, 3000);
	var timer = setInterval(function () {
		var hi = $('#tipsDiv .hi');
		var value = +(hi.html().replace('秒', ''));
		if (value > 1) {
			hi.html(--value + '秒');
		} else {
			clearInterval(timer);
		}
	}, 1000);
}());
